<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Collections</title>
    <link rel="stylesheet" href="/ai-collections/static/css/style.css">
    <link rel="icon" type="image/png" href="/ai-collections/static/images/logo.png">
    <style>
        /* 添加用户菜单下拉样式 */
        .user-menu {
            position: relative;
            cursor: pointer;
        }

        .user-menu:hover .dropdown-menu {
            display: block;
        }

        .dropdown-menu {
            display: none;
            position: absolute;
            top: 100%;
            right: 0;
            background-color: var(--card-background);
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            padding: 0.5rem 0;
            min-width: 150px;
            z-index: 1000;
        }

        .dropdown-menu a {
            display: block;
            padding: 0.5rem 1rem;
            color: var(--text-color);
            text-decoration: none;
            transition: background-color 0.2s;
        }

        .dropdown-menu a:hover {
            background-color: var(--background-color);
        }

        .dropdown-menu .divider {
            height: 1px;
            background-color: var(--border-color);
            margin: 0.5rem 0;
        }

        /* 添加卡片文字溢出处理样式 */
        .channel-card {
            overflow: hidden;
        }

        .channel-card h3 {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 10px;
        }

        .status-bar {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* 添加用户信息区域按钮样式 */
        .user-buttons {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            margin-top: 1.5rem;
        }
        
        .user-button {
            display: block;
            padding: 0.5rem 0.75rem;
            background-color: var(--card-background);
            color: var(--text-color);
            border: 1px solid var(--border-color);
            border-radius: 0.25rem;
            text-align: center;
            text-decoration: none;
            font-size: 0.9rem;
            transition: all 0.2s;
        }
        
        .user-button:hover {
            background-color: var(--background-color);
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        .user-button.primary {
            background-color: #4a88e5;
            color: white;
            border-color: #4a88e5;
        }
        
        .user-button.primary:hover {
            background-color: #3a78d5;
        }
        
        .user-button.danger {
            background-color: #e54a4a;
            color: white;
            border-color: #e54a4a;
        }
        
        .user-button.danger:hover {
            background-color: #d53a3a;
        }
        
        /* 加载提示样式 */
        .toast.loading {
            display: flex;
            align-items: center;
            background-color: #3498db;
            color: white;
        }

        .spinner {
            margin-right: 10px;
            display: flex;
        }

        .spinner > div {
            width: 12px;
            height: 12px;
            background-color: white;
            border-radius: 100%;
            display: inline-block;
            animation: bounce 1.4s infinite ease-in-out both;
            margin-right: 4px;
        }

        .spinner .bounce1 {
            animation-delay: -0.32s;
        }

        .spinner .bounce2 {
            animation-delay: -0.16s;
        }

        @keyframes bounce {
            0%, 80%, 100% { 
                transform: scale(0);
            } 40% { 
                transform: scale(1.0);
            }
        }
    </style>
</head>
<body>
    <div id="toastContainer" class="toast-container"></div>

    <header class="header">
        <div class="logo">
            <img src="/ai-collections/static/images/logo.png" alt="Logo" class="logo-img">
            <span>AI Collections</span>
        </div>
        <nav>
            <a href="/ai-collections/" class="active">首页</a>
            <a href="/ai-collections/notice">公告</a>
        </nav>
        <div class="user-menu">
            <span class="avatar">{{if .UserInfo.IsGuest}}游客{{else}}{{.UserInfo.Username}}{{end}}</span>
        </div>
    </header>

    <div class="container">
        <aside class="sidebar">
            <div class="user-info">
                <h2>{{if .UserInfo.IsGuest}}您好，游客{{else}}欢迎您，{{.UserInfo.Username}}{{end}}</h2>
                <p>{{if .UserInfo.IsGuest}}感谢访问ChatGPT服务{{else}}感谢使用ChatGPT服务{{end}}</p>
                <div class="info-item">
                    <label>用户名:</label>
                    <span>{{.UserInfo.Username}}</span>
                </div>
                <div class="info-item">
                    <label>邮箱:</label>
                    <span>{{.UserInfo.Email}}</span>
                </div>
                <div class="info-item">
                    <label>角色:</label>
                    <span>{{if .UserInfo.IsOwner}}管理员{{else}}{{range $index, $role := .UserInfo.Roles}}{{if $index}}, {{end}}{{$role}}{{end}}{{end}}</span>
                </div>
                
                {{if not .UserInfo.IsGuest}}
                <div class="user-buttons">
                    <a href="/my-roles" class="user-button primary">角色管理</a>
                    <a href="/logout" class="user-button danger">退出登录</a>
                </div>
                {{end}}
            </div>
        </aside>

        <main class="content">
            <div class="channel-tabs">
                {{if .Config.ShowClaude}}
                <div class="tab active" data-channel="Claude">
                    <span class="icon">🌟</span>
                    claude
                </div>
                {{end}}
                {{if .Config.ShowPlus}}
                <div class="tab" data-channel="Plus">
                    <span class="icon">💎</span>
                    chatGPT
                </div>
                {{end}}
                {{if .Config.ShowFingerprint}}
                <div class="tab" data-channel="Fingerprint">
                    <span class="icon">🎁</span>
                    指纹
                </div>
                {{end}}
            </div>

            <div class="channel-list">
                {{if and .Config.ShowClaude (index .Channels "Claude")}}
                <div class="channel-group claude-channels" style="display: flex; flex-wrap: wrap; gap: 1.5rem; width: 100%;">
                    {{range $channel := index .Channels "Claude"}}
                    <div class="channel-card" data-car-id="{{$channel.ID}}" data-channel-type="{{$channel.Type}}" style="flex: 0 0 calc(33.333% - 1.5rem); min-width: 280px;">
                        <div class="card-header">
                            <span class="status {{$channel.Status}}">{{$channel.Status}}</span>
                            <h3>{{$channel.Name}}</h3>
                        </div>
                        <div class="card-body">
                            <div class="status-bar">
                                <span class="real-status {{$channel.StatusClass}}">{{$channel.RealStatus}}</span>
                                {{if $channel.IdleStatus}}
                                <span class="idle-status">{{$channel.IdleStatus}}</span>
                                {{end}}
                            </div>
                        </div>
                    </div>
                    {{end}}
                </div>
                {{end}}

                {{if and .Config.ShowPlus (index .Channels "Plus")}}
                <div class="channel-group plus-channels" style="display: flex; flex-wrap: wrap; gap: 1.5rem; width: 100%;">
                    {{range $channel := index .Channels "Plus"}}
                    <div class="channel-card" data-car-id="{{$channel.ID}}" data-channel-type="{{$channel.Type}}" style="flex: 0 0 calc(33.333% - 1.5rem); min-width: 280px;">
                        <div class="card-header">
                            <span class="status {{$channel.Status}}">{{$channel.Status}}</span>
                            <h3>{{$channel.Name}}</h3>
                        </div>
                        <div class="card-body">
                            <div class="status-bar">
                                <span class="real-status {{$channel.StatusClass}}">{{$channel.RealStatus}}</span>
                                {{if $channel.IdleStatus}}
                                <span class="idle-status">{{$channel.IdleStatus}}</span>
                                {{end}}
                            </div>
                        </div>
                    </div>
                    {{end}}
                </div>
                {{end}}

                {{if and .Config.ShowFingerprint (index .Channels "Fingerprint")}}
                <div class="channel-group fingerprint-channels" style="display: flex; flex-wrap: wrap; gap: 1.5rem; width: 100%;">
                    {{range $channel := index .Channels "Fingerprint"}}
                    <div class="channel-card" data-car-id="{{$channel.ID}}" data-channel-type="{{$channel.Type}}" style="flex: 0 0 calc(33.333% - 1.5rem); min-width: 280px;">
                        <div class="card-header">
                            <span class="status {{$channel.Status}}">{{$channel.Status}}</span>
                            <h3>{{$channel.Name}}</h3>
                        </div>
                        <div class="card-body">
                            <div class="status-bar">
                                <span class="real-status {{$channel.StatusClass}}">{{$channel.RealStatus}}</span>
                                {{if $channel.IdleStatus}}
                                <span class="idle-status">{{$channel.IdleStatus}}</span>
                                {{end}}
                            </div>
                        </div>
                    </div>
                    {{end}}
                </div>
                {{end}}
            </div>
        </main>
    </div>

    <script>
    function showToast(message, type = 'warning') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.textContent = message;
        container.appendChild(toast);

        // 3秒后自动移除
        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease-out forwards';
            setTimeout(() => {
                container.removeChild(toast);
            }, 300);
        }, 3000);
    }
    
    // 显示加载提示
    function showLoadingToast(message) {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        const id = 'loading-toast-' + Date.now();
        toast.id = id;
        toast.className = 'toast loading';
        
        // 创建加载指示器
        const spinner = document.createElement('div');
        spinner.className = 'spinner';
        spinner.innerHTML = '<div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div>';
        
        // 添加消息
        const messageElem = document.createElement('span');
        messageElem.textContent = message;
        
        toast.appendChild(spinner);
        toast.appendChild(messageElem);
        container.appendChild(toast);
        
        return id; // 返回ID以便后续可以关闭它
    }

    // 隐藏加载提示
    function hideLoadingToast(id) {
        const toast = document.getElementById(id);
        if (toast) {
            toast.style.animation = 'slideOut 0.3s ease-out forwards';
            setTimeout(() => {
                const container = document.getElementById('toastContainer');
                if (container.contains(toast)) {
                    container.removeChild(toast);
                }
            }, 300);
        }
    }

    // 生成随机授权码
    function generateRandomToken(length = 32) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        const charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }

    // 处理卡片点击事件，根据频道类型跳转到不同地址或调用客户端
    function handleCardClick() {
        const cards = document.querySelectorAll('.channel-card');
        cards.forEach(card => {
            card.addEventListener('click', async function() {
                const carId = this.getAttribute('data-car-id');
                const channelType = this.getAttribute('data-channel-type');
                
                try {
                    // 显示加载中提示
                    showToast("正在准备跳转...", "info");
                    
                    // 获取当前激活的页签
                    const activeTab = document.querySelector('.tab.active');
                    const activeChannel = activeTab ? activeTab.getAttribute('data-channel') : 'Claude';
                    
                    // 如果是Plus频道，先清除Claude的session cookie
                    if (channelType === 'Plus') {
                        try {
                            const cookieResponse = await fetch('/ai-collections/clear-claude-cookie', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                }
                            });
                            
                            if (cookieResponse.ok) {
                                console.log("已通过后端清除Claude session cookie");
                            } else {
                                console.error("清除cookie失败");
                            }
                        } catch (cookieError) {
                            console.error("清除cookie时发生错误:", cookieError);
                        }
                    }
                    
                    
                    // 为Fingerprint类型做特殊处理
                    if (channelType === 'Fingerprint') {
                        // 弹窗确认是否打开客户端
                        if(confirm("即将拉起ixBrowser客户端，是否继续？")) {
                            try {
                                // 显示加载状态
                                const loadingToastId = showLoadingToast("正在启动客户端...");
                                
                                // 创建请求数据
                                const requestData = {
                                    "profile_id": parseInt(carId),
                                    "args": [
                                        "--disable-extension-welcome-page"
                                    ],
                                    "load_extensions": true,
                                    "load_profile_info_page": true,
                                    "cookies_backup": true,
                                    "cookie": ""
                                };
                                
                                // 方法1: 尝试使用no-cors模式
                                fetch('http://127.0.0.1:53200/api/v2/profile-open', {
                                    method: 'POST',
                                    mode: 'no-cors', // 关键设置
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify(requestData)
                                }).then(() => {
                                    // 移除加载提示
                                    hideLoadingToast(loadingToastId);
                                    showToast("客户端启动成功", "success");
                                }).catch(error => {
                                    console.error("方法1失败:", error);
                                    
                                    // 方法2: 使用动态创建的表单提交
                                    try {
                                        const form = document.createElement('form');
                                        form.method = 'POST';
                                        form.action = 'http://127.0.0.1:53200/api/v2/profile-open';
                                        form.target = '_blank';
                                        
                                        const input = document.createElement('input');
                                        input.type = 'hidden';
                                        input.name = 'data';
                                        input.value = JSON.stringify(requestData);
                                        
                                        form.appendChild(input);
                                        document.body.appendChild(form);
                                        form.submit();
                                        document.body.removeChild(form);
                                        
                                        // 移除加载提示
                                        hideLoadingToast(loadingToastId);
                                        showToast("客户端启动中(方法2)", "success");
                                    } catch (err) {
                                        console.error("方法2失败:", err);
                                        
                                        // 方法3: 尝试通过窗口打开
                                        const urlParams = new URLSearchParams();
                                        urlParams.append('data', JSON.stringify(requestData));
                                        window.open(`http://127.0.0.1:53200/api/v2/profile-open?${urlParams.toString()}`, '_blank');
                                        
                                        // 移除加载提示
                                        hideLoadingToast(loadingToastId);
                                        showToast("客户端启动中(方法3)，如未启动，请检查客户端是否已安装", "info");
                                    }
                                });
                            } catch (clientError) {
                                console.error('Client API Error:', clientError);
                                showToast("无法连接到ixBrowser客户端，请确保客户端已安装并启动", "error");
                            }
                        }
                    } else {
                        // 生成token请求
                        const response = await fetch('/ai-collections/create-token', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                carId: carId,
                                channelType: channelType,
                                activeTab: activeChannel // 发送当前激活的页签信息
                            }),
                        });
                        
                        // 检查响应状态
                        if (response.status === 401 || response.status === 403) {
                            // 未登录或权限不足的情况
                            showToast("您尚未登录，请先登录", "error");
                            
                            // 延迟1秒后重定向到登录页面
                            setTimeout(() => {
                                window.location.href = "/list";
                            }, 1000);
                            return; // 提前退出函数
                        }
                        
                        if (!response.ok) {
                            throw new Error('Token generation failed');
                        }
                        
                        const data = await response.json();
                        const userToken = data.token;
                        
                        // 显示令牌使用说明
                        showToast(`令牌生成成功，有效期3分钟，仅能使用一次`, "success");
                        // 其他类型仍然使用原来的重定向逻辑
                        let redirectUrl = '';
                        if (channelType === 'Claude') {
                            redirectUrl = `/claude/auth/logintoken?carid=${carId}&usertoken=${userToken}`;
                        } else if (channelType === 'Plus') {
                            redirectUrl = `/gpt/auth/logintoken?carid=${carId}&usertoken=${userToken}`;
                        }
                        
                        if (redirectUrl) {
                            // 延迟跳转，让用户看到提示
                            setTimeout(() => {
                                window.location.href = redirectUrl;
                            }, 1000);
                        }
                    }
                } catch (error) {
                    console.error('Error:', error);
                    showToast("跳转准备失败，请重试", "error");
                }
            });
        });
    }

    // 自动刷新状态
    async function refreshStatus() {
        try {
            const response = await fetch(window.location.href);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            location.reload();
        } catch (error) {
            showToast('网络连接不稳定，请检查网络后重试', 'error');
        }
    }

    // 每60秒刷新一次
    setInterval(refreshStatus, 60000);

    // 标签页切换功能
    document.addEventListener('DOMContentLoaded', function() {
        const tabs = document.querySelectorAll('.tab');
        const channelGroups = document.querySelectorAll('.channel-group');

        // 从后端获取上次选择的频道
        const lastSelectedChannel = "{{.ActiveTab}}";
        
        // 如果没有可见的标签，直接返回
        if (tabs.length === 0) {
            return;
        }
        
        // 检查上次选择的频道是否可见
        let tabFound = false;
        tabs.forEach(tab => {
            const channelType = tab.getAttribute('data-channel');
            if (channelType === lastSelectedChannel) {
                tab.classList.add('active');
                tabFound = true;
            } else {
                tab.classList.remove('active');
            }
        });
        
        // 如果上次选择的页签不可见或不存在，选择第一个可见的页签
        if (!tabFound && tabs.length > 0) {
            tabs[0].classList.add('active');
            const firstChannel = tabs[0].getAttribute('data-channel');
            localStorage.setItem('selectedChannel', firstChannel);
        }
        
        // 更新频道组的显示状态
        channelGroups.forEach(group => {
            const groupName = group.classList[1].split('-')[0]; // 获取频道名称 (如 "claude" 从 "claude-channels")
            const activeTab = document.querySelector('.tab.active');
            const activeChannel = activeTab ? activeTab.getAttribute('data-channel') : null;
            
            if (activeChannel && groupName.toLowerCase() === activeChannel.toLowerCase()) {
                group.style.display = 'flex';
            } else {
                group.style.display = 'none';
            }
        });

        // 为每个标签添加点击事件
        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                // 取消所有标签的激活状态
                tabs.forEach(t => t.classList.remove('active'));
                
                // 激活当前点击的标签
                this.classList.add('active');
                
                // 获取当前标签对应的频道类型
                const channelType = this.getAttribute('data-channel');
                
                // 保存当前选择到localStorage
                localStorage.setItem('selectedChannel', channelType);
                
                // 隐藏所有频道组
                channelGroups.forEach(group => {
                    group.style.display = 'none';
                });
                
                // 显示当前选中的频道组
                const activeGroup = document.querySelector(`.${channelType.toLowerCase()}-channels`);
                if (activeGroup) {
                    activeGroup.style.display = 'flex';
                }
            });
        });
        
        // 初始化卡片点击事件
        handleCardClick();
    });
    </script>
    
    {{if .Error}}
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        showToast("{{.Error}}", 'error');
    });
    </script>
    {{end}}
</body>
</html> 